package com.tom.demo.service.system.impl;

import cn.hutool.core.lang.Snowflake;
import com.tom.demo.common.entity.SysMenu;
import com.tom.demo.common.enumeration.ResponseEnum;
import com.tom.demo.common.exception.CustomException;
import com.tom.demo.common.response.Result;
import com.tom.demo.common.utils.RecursiveMenuUtil;
import com.tom.demo.common.utils.SecurityUtils;
import com.tom.demo.dto.MenuSearchDto;
import com.tom.demo.mapper.SysMenuMapper;
import com.tom.demo.service.system.MenuService;
import com.tom.demo.vo.MenuOptionsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private Snowflake snowflake;

    @Override
    public Result list() {
        List<SysMenu> sysMenuList = sysMenuMapper.findMenuAll();
        //构建树级别菜单
        List<SysMenu> sysMenus = RecursiveMenuUtil.buildMenuTree(sysMenuList);
        return Result.success(sysMenus);
    }

    @Override
    public Result deleteByMenuId(String menuId) {
        List<SysMenu> sysMenuList = sysMenuMapper.findByParentId(menuId);
        if(!CollectionUtils.isEmpty(sysMenuList)){
            throw new CustomException(ResponseEnum.MENU_DATA_EXIST);
        }
        int row = sysMenuMapper.deleteByPrimaryKey(menuId);
        return row > 0 ? Result.success():Result.error("删除失败");
    }

    @Override
    public Result optionsTree(String menuType) {
        Set<String> types = new HashSet<>();
        types.add("M");
        types.add(menuType);
        List<SysMenu> sysMenus = sysMenuMapper.findByMenuType(types);
        MenuOptionsVo menuOptionsVo = RecursiveMenuUtil.buildMenuOptions(sysMenus);
        return Result.success(menuOptionsVo);
    }

    @Override
    public Result insertMenu(SysMenu sysMenu) {
        sysMenu.setMenuId(snowflake.nextIdStr());
        sysMenu.setCreateTime(new Date());
        String userName = SecurityUtils.getLoginUserName();
        sysMenu.setCreateBy(userName);
        sysMenu.setVisible(false);
        int row = sysMenuMapper.insert(sysMenu);
        return row > 0 ? Result.success():Result.error("添加失败");
    }
}
